from info.models import User, News,Category
from info.modules.index import index_blu
from info import redis_store
from flask import render_template, current_app, redirect, send_file, session
from info import constants

@index_blu.route("/")
def index():
    user_id = session.get("user_id")

    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)


    # data = {
    #     "user_info":{
    #         "nick_name":"laowang",
    #         "mobile":"6666"
    #     }
    # }
    # 首页点击排行
    clicks_news = []
    try:
        clicks_news = News.query.order_by(News.click.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)

    clicks_news_li = []
    for news_obj in clicks_news:
        clicks_news_dict = news_obj.to_basic_dict()
        clicks_news_li.append(clicks_news_dict)

    # 显示新闻分类
    categorys = []

    try:
        categorys = Category.query.all()

    except Exception as e:
        current_app.logger.error(e)

    # categorys_li = []
    # for category in categorys:
    #     categorys_dict = category.to_dict()
    #     categorys_li.append(categorys_dict)

    # 使用列表推导式返回[{},{},{}数据]
    categorys_li = [category.to_dict() for category in categorys]


    data = {
        "user_info":user.to_dict() if user else None,
        "clicks_news_li":clicks_news_li,
        "categorys":categorys_li
    }

    return render_template("news/index.html",data=data)







@index_blu.route("/favicon.ico")
def favicon():
    # redirect("/static/news/favicon.ico")
   return current_app.send_static_file("news/favicon.ico")
   #  return send_file("/static/news/favicon.ico")